<template>
  <div class="user-list">
    <!-- 查询表单 -->
    <a-row :gutter="16" class="product-row">
      <a-col :span="8">
        <a-input
            v-model="id"
            placeholder="用户编号"
            addon-before="用户名"
        />
      </a-col>
      <a-col :span="8">
        <a-date-picker
            v-model="startDate"
            placeholder="开始时间"
            style="width: 100%"
            format="YYYY-MM-DD"
        />
      </a-col>
      <a-col :span="8">
        <a-date-picker
            v-model="endDate"
            placeholder="结束时间"
            style="width: 100%"
            format="YYYY-MM-DD"
        />
      </a-col>
      <a-col :span="8" style="margin: 16px 0px">
        <a-button type="primary" @click="handleSearch">查询</a-button>
        <a-button @click="handleReset" style="margin-left: 4px;">重置</a-button>
      </a-col>
    </a-row>

    <!-- 表格 -->
    <a-table :data-source="usersdate" :columns="columns" row-key="id" :pagination="false" class="product-table">
      <template slot="avatar" slot-scope="text, record">
        <a-avatar :src="record.avatar"/>
      </template>
      <template slot="action" slot-scope="text, record">
        <a @click="handleDetail(record)">详情</a>
        <a-divider type="vertical"/>
        <a-dropdown>
          <a @click="handleMoney(record)">
            更多
          </a>
          <template #overlay>
            <a-menu>
              <a-menu-item @click="showBalanceModal(record)">
                <a href="javascript:;">调整余额</a>
              </a-menu-item>
              <a-menu-item @click="showPointsModal(record)">
                <a href="javascript:;">调整积分</a>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
    </a-table>

    <!-- 用户详情模态框 -->
    <a-modal title="用户详情"
             :visible="isDetailModalVisible"
             @ok="handleDetailModalCancel"
             @cancel="handleDetailModalCancel"
    >
      <p>用户名称：{{ record.name }}</p>
      <p>账号：{{ record.username }}</p>
      <p>手机号码：{{ record.mobile }}</p>
      <p>金额：{{ record.money }}</p>
      <p>积分：{{ record.infinitesimalrechnung }}</p>
      <p>性别：{{ record.sex }}</p>
      <p>登陆ip：{{ record.lastLoginIp }}</p>
      <p>登陆时间：{{ record.lastLoginTime }}</p>
      <p>创建时间：{{ record.createTime }}</p>
    </a-modal>

    <!-- 调整余额模态框 -->
    <a-modal title="调整余额"
             :visible="isBalanceModalVisible"
             @ok="adjustPoints"
             @cancel="showBalanceCancel"
    >
      <p>用户：{{ record.username }}</p>
      <p>当前余额：{{ record.money }}</p>
      <a-input v-model="adjustment" min="0"/>
    </a-modal>

    <!-- 调整积分模态框 -->
    <a-modal title="调整积分"
             :visible="isPointsModalVisible"
             @ok="InfinitesPoints"
             @cancel="InfinitesshowBalanceCancel"
    >
      <p>用户：{{ record.username }}</p>
      <p>当前积分：{{ record.infinitesimalrechnung }}</p>
      <a-input v-model="adjustment"/>
    </a-modal>
  </div>
</template>

<script>
import {Row, Col, Input, DatePicker, Button, Table, Avatar, Divider, Dropdown, Modal} from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import {METHOD, request} from "@/utils/request";

export default {
  components: {
    'a-row': Row,
    'a-col': Col,
    'a-input': Input,
    'a-date-picker': DatePicker,
    'a-button': Button,
    'a-table': Table,
    'a-avatar': Avatar,
    'a-divider': Divider,
    'a-dropdown': Dropdown,
    'a-modal': Modal,
  },
  data() {
    return {
      username: '',
      startDate: '',
      endDate: '',
      source: '',
      mobile: '',
      infinitesimalrechnung: '',
      sex: '',
      lastLoginIp: '',
      lastLoginTime: '',
      createTime: '',
      money: '',
      adjustment: 0,
      isDetailModalVisible: false,
      isBalanceModalVisible: false,
      isPointsModalVisible: false,
      record: {},

      usersdate: [
        // {
        //   id: '1',
        //   username: '用户22001799',
        //   avatar: require('@/pages/list/menu/images/iPhone14.png'),
        //   account: 'wzy666',
        //   phone: '19846336468',
        //   gender: '男',
        //   source: '手机H5',
        //   registerTime: '2024-12-10 22:49:49',
        //   balance: 100,
        //   integral: 200,
        // },
        // {
        //   id: '21',
        //   username: '用户2200das9',
        //   avatar: 'https://img2.baidu.com/it/u=3143892369,962147081&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=800',
        //   account: 'wzy666',
        //   phone: '18825252525',
        //   gender: '女',
        //   source: '手机H5',
        //   registerTime: '2024-12-10 22:49:49',
        //   balance: 150,
        //   integral: 300,
        // },
        // {
        //   id: '3',
        //   username: '用户2203129',
        //   avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
        //   account: 'wzy666',
        //   phone: '13886435486',
        //   gender: '男',
        //   source: '手机H5',
        //   registerTime: '2024-12-10 22:49:49',
        //   balance: 120,
        //   integral: 250,
        // },
      ],
      columns: [
        {
          title: '用户编号',
          dataIndex: 'id',
          key: 'id',
        },
        {
          title: '头像',
          dataIndex: 'avatar',
          key: 'avatar',
          scopedSlots: {customRender: 'avatar'},
        },
        {
          title: '昵称',
          dataIndex: 'name',
          key: 'name',
        },
        {
          title: '账号',
          dataIndex: 'username',
          key: 'username',
        },
        {
          title: '手机号码',
          dataIndex: 'mobile',
          key: 'mobile',
        },
        {
          title: '金额',
          dataIndex: 'money',
          key: 'money',
        },
        {
          title: '积分',
          dataIndex: 'infinitesimalrechnung',
          key: 'infinitesimalrechnung',
        },
        {
          title: '性别',
          dataIndex: 'sex',
          key: 'sex',
        },
        {
          title: '登陆ip',
          dataIndex: 'lastLoginIp',
          key: 'lastLoginIp',
        },
        {
          title: '登陆时间',
          dataIndex: 'lastLoginTime',
          key: 'lastLoginTime',
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: {customRender: 'action'},
        },
      ],
    };
  },
  mounted() {
    this.fetchData();  // 调用 fetchData 获取数据
  },
  methods: {
    handleSearch() {
      console.log('查询:', this.username, this.startDate, this.endDate, this.source);
    },
    handleReset() {
      this.username = '';
      this.startDate = '';
      this.endDate = '';
      this.source = '';
    },
    //打开详情模态框
    handleDetail(record) {
      this.record = record;
      this.isDetailModalVisible = true;
    },
    //关闭详情模态框
    handleDetailModalCancel() {
      this.isDetailModalVisible = false;
    },
    //打开余额调整模态框
    showBalanceModal(record) {
      this.record = record;
      this.isBalanceModalVisible = true;
    },
    //关闭详情模态框
    showBalanceCancel() {
      this.isBalanceModalVisible = false;
    },
    InfinitesshowBalanceCancel() {
      this.isPointsModalVisible = false;
    },
    //关闭余额调整模态框
    adjustPoints() {
      let add = parseFloat(this.adjustment).toFixed(2);  // 将用户输入的数字转换为浮动类型
      try {
        // 调用后端 API 获取用户信息
        request(
            `${window.location.protocol}//${window.location.hostname}:8080/api/user/updatebalance`,
            METHOD.POST
            , {
              username: this.record.username,
              money: add,  // 字符串，保留两位小数
              disable: 2
            }, {
              headers: {
                Accept: 'application/json',
                Authorization: `Bearer ` + localStorage.getItem("token")
              }
            }
        ).then(() => {
          this.$message.success('金额调整成功');
          this.fetchData();  // 刷新数据
          this.isBalanceModalVisible = false;  // 关闭模态框
        }).catch(error => {
          // 如果发生错误，显示错误信息
          console.error(error);
          this.$message.error('出现错误，请稍后再试');
          this.isBalanceModalVisible = false;  // 关闭模态框，即使发生错误
        });
      } catch (error) {
        console.error(error);
        this.$message.error('出现错误，请稍后再试');
        this.isBalanceModalVisible = false;
      }
    },
    //打开积分调整模态框
    showPointsModal(record) {
      this.record = record;
      this.isPointsModalVisible = true;
    },
    //关闭积分调整模态框
    InfinitesPoints() {
      let add = parseFloat(this.adjustment).toFixed(2);  // 将用户输入的数字转换为浮动类型
      try {
        // 调用后端 API 获取用户信息
        request(
            `${window.location.protocol}//${window.location.hostname}:8080/api/user/UpdateIntegration`,
            METHOD.POST
            , {
              username: this.record.username,
              Infinitesimalrechnung: add,  // 字符串，保留两位小数
              disable: 2
            }, {
              headers: {
                Accept: 'application/json',
                Authorization: `Bearer ` + localStorage.getItem("token")
              }
            }
        ).then(() => {
          this.$message.success('积分调整成功');
          this.fetchData();  // 刷新数据
          this.isPointsModalVisible = false;  // 关闭模态框
        }).catch(error => {
          // 如果发生错误，显示错误信息
          console.error(error);
          this.$message.error('出现错误，请稍后再试');
          this.isPointsModalVisible = false;  // 关闭模态框，即使发生错误
        });
      } catch (error) {
        console.error(error);
        this.$message.error('出现错误，请稍后再试');
      }
      this.isPointsModalVisible = false;
    },
    async fetchData() {
      try {
        // 调用后端 API 获取用户信息
        const response = await request(
            `${window.location.protocol}//${window.location.hostname}:8080/api/user/infoAll`,
            METHOD.GET
            , {
              headers: {
                Accept: 'application/json',
                Authorization: `Bearer ` + localStorage.getItem("token")
              }
            }
        );
        let userData = response.data.data;
        // 遍历订单数据，设置 username
        userData.forEach(item => {
          item.name = item.name == null || item.name === "" ? "乐购" + (item.mobile ? item.mobile.slice(-4) : '') : item.name;
          item.avatar = item.avatar == null || item.avatar === "" ? `${window.location.protocol}//${window.location.hostname}:8080/api/uploads/default_avatar.png` : item.avatar;
        });

        this.usersdate = userData;
      } catch (error) {
        console.error(error);
      }
    },
    computed: {
      // 计算属性确保值总是带有两位小数
      formattedAdjustment: {
        get() {
          return this.adjustment.toFixed(2); // 格式化为带有两位小数
        },
        set(value) {
          // 当用户修改输入时，将其转换为浮动的数字
          this.adjustment = parseFloat(value);
        }
      }
    }
  },
};
</script>

<style scoped>
.product-row {
  background-color: white;
  padding: 16px;
  margin-bottom: 16px;
  border-radius: 10px;
}

.product-table {
  background-color: whitesmoke;
}

.user-list {
  padding: 20px;
  font-family: Arial, sans-serif;
}

.a-space {
  display: flex;
  justify-content: flex-end;
}

.a-button {
  margin-right: 8px;
}
</style>
